<?php

/**
 * @file
 * Contains Ubercart Pasargad Bank "Paypaad" Payment callbacks & internal helpers.
 */

/**
 * Menu callback for cart/paypaad/% path, handling gateway response.
 *
 * @param $status
 *   Paypaad gateway response status.
 *   - success
 *   - failure
 */
function uc_paypaad_response($status) {
  // Load UC order object.
  $order = uc_order_load((int) $_SESSION['cart_order']);

  // Handle a successfull Paypaad payment.
  if ($status == 'success' && ($response = paypaad_response()) && $order) {
    // Enquiry payment.
    $transaction = paypaad_trace($response['transaction_reference'], array(), paypaad_settings('trace_uri', 'uc', PAYPAAD_TRACE_URI));
    // Validate Paypaad transaction.
    if (_uc_paypaad_transaction_validate($transaction, $response, $order)) {
      // Save Paypaad payment transaction.
      global $user;
      $entity_path = $user->uid ? "user/{$user->uid}/order/{$order->order_id}" : '';
      paypaad_save($transaction, $entity_path, 'uc_paypaad');
      // UC order completion workflow...
      $comment = t('Total amount of "!amount" has been successfully paid via "!method". Payment transaction reference is "!reference".',
        array(
          '!method' => ucwords($order->payment_method),
          '!reference' => $transaction['transaction_reference_id'],
          '!amount' => uc_currency_format(intval($transaction['amount']), TRUE, TRUE, NULL),
        )
      );
      // Enter payment for the order.
      uc_payment_enter($order->order_id, $order->payment_method, $order->order_total, 0, array('reference' => $transaction['transaction_reference_id']), $comment);
      // Let her know the reference number.
      drupal_set_message($comment);
      // Empty user cart, Update order status, register customer if required
      // and log her in. Also get the themed output of order completion page.
      $message = uc_cart_complete_sale($order, TRUE);
      // Notify user about order completion.
      drupal_set_message($message);
      // Log comments to order, for both customer & admin.
      // Needs to be called after uc_cart_complete_sale().
      uc_order_comment_save($order->order_id, 0, $comment);
      uc_order_comment_save($order->order_id, 0, $comment, 'order', uc_order_state_default('post_checkout'), TRUE);
      // And redirect to the proper end!
      drupal_goto(variable_get('uc_cart_checkout_complete_page', 'cart'));
    }
  }

  // Handle a failed payment, Notify user.
  drupal_set_message(t('There were a problem processing your payment via Paypaad, please try again.'), 'error');
  // Log a watchdog error.
  watchdog(
    'uc_paypaad',
    'Paypaad payment failed for order ID %order.',
    array('%order' => $order_id),
    WATCHDOG_ERROR
  );
  // Redirect to checkout page.
  drupal_goto('cart/checkout');
}

/**
 * Internal helper to validate a Paypaad payment transaction.
 *
 * @param $transaction
 *   Transaction object generated by paypaad_trace().
 * @param $response
 *   Response array generated by paypaad_response().
 * @param $order
 *   Current customer UC order object.
 *
 * @return
 *   Boolean value.
 *
 * @see paypaad_trace()
 * @see paypaad_response()
 * @see uc_paypaad_response()
 */
function _uc_paypaad_transaction_validate($transaction, $response, $order) {
  // Value of $transaction->result is not boolean typed.
  if ($transaction['result'] == 'true' &&
      $transaction['invoice_number'] == $order->order_id &&
      intval($transaction['amount']) == intval($order->order_total) &&
      $transaction['invoice_date']   == $response['invoice_date']   &&
      $transaction['invoice_number'] == $response['invoice_number'] &&
      $transaction['merchant_code']  == paypaad_settings('merchant', 'uc') &&
      $transaction['terminal_code']  == paypaad_settings('terminal', 'uc') &&
      $transaction['transaction_reference_id'] == $response['transaction_reference']) {
    return TRUE;
  }
  // Validation failed.
  return FALSE;
}

